package com.willian.flutterapp.flutterplugin;

import android.app.Activity;
import android.util.Log;

import java.util.concurrent.TimeUnit;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.PluginRegistry;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class FlutterPluginCounter implements EventChannel.StreamHandler {

    public static String CHANNEL = "com.willian.flutterapp/native_send_plugin";
    static EventChannel channel;
    public EventChannel.EventSink eventSink;

    private Activity activity;
    private FlutterPluginCounter(Activity activity) {
        this.activity = activity;
    }

    public static FlutterPluginCounter registerWith(FlutterEngine flutterEngine, FlutterActivity activity) {
        channel = new EventChannel(flutterEngine.getDartExecutor(), CHANNEL);
        FlutterPluginCounter instance = new FlutterPluginCounter(activity);
        channel.setStreamHandler(instance);
        return instance;
    }

    @Override
    public void onListen(Object obj, final EventChannel.EventSink eventSink) {

        this.eventSink = eventSink;

        Observable.interval(1000, TimeUnit.MILLISECONDS).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) { }

            @Override
            public void onNext(Long aLong) {
                eventSink.success(aLong.intValue());
            }

            @Override
            public void onError(Throwable e) {
                eventSink.error("计时器异常", "异常", e.getMessage());
            }

            @Override
            public void onComplete() { }
        });
    }

    @Override
    public void onCancel(Object o) {
        Log.i("FlutterPluginCounter", "FlutterPluginCounter:onCancel");
    }
}